#ifndef _ANDROID_H
#define _ANDROID_H

#include "music.h"
#include <netinet/in.h>
#include <pthread.h>
#include <stdint.h>
#include <stdio.h>
#include <sys/socket.h>

struct {
  const uint8_t READY_RECV;
  const uint8_t DEV_ERR;
} static const AndroidRespType = {.READY_RECV = 0x01, .DEV_ERR = 0x00};

struct {
  const uint8_t ONLINE;
  const uint8_t TRANSFER;
} static const Resp2AndroidType = {.ONLINE = 0x01, .TRANSFER = 0x02};

struct {
  const uint8_t ANDROID_ONLINE;    // online offline
  const uint8_t ANDROID_HEARTBEAT; // heartbeat
  const uint8_t RESP_FROM_ANDROID; // response from android
  const uint8_t RESP_2_ANDROID;    // response to andorid
} static const MsgStatus = {.ANDROID_ONLINE = 0x01,
                            .ANDROID_HEARTBEAT = 0x02,
                            .RESP_FROM_ANDROID = 0x03,
                            .RESP_2_ANDROID = 0x04};

/* online and offline */
typedef struct {
  uint8_t status;        // 1byte, fixed to 0x01
  uint8_t online;        // 1byte, 0x01 if online, 0x00 if offline
  uint8_t login_time[9]; // 8bytes, yyyymmdd
  uint8_t dev_id;        // 1byte, 0x01-0x0a
  uint8_t check_bit;
} AndroidOnlineMsg;

/* android heatbeat */
typedef struct {
  uint8_t status; // 1byte, fixed to 0x02
  uint8_t dev_id; // 1byte, 0x01-0x0a
} AndroidHeartbeat;

typedef struct {
  uint8_t status; // 1byte, fixed to 0x03

  /* 0x01 if android prepare to receive file
     0x00 if the device is abnormal */
  uint8_t resp_type;
} RespFromAndroid;

typedef struct {
  int connfd;
  struct sockaddr_in caddr;
  socklen_t addrlen;
  pthread_t tid;

  char login_time[9];
  uint8_t dev_id;
} AndroidConn;

char *mkresp2android(uint8_t resp_type, uint8_t file_num,
                     const uint8_t file_sizes[], int *psize);

void android_init();
void android_startup();
int get_connfd_by_dev_id(uint8_t dev_id);
uint8_t strid2uint8(const char *idstr);
void add_conn(int connfd, int dev_id);
void delete_conn(int connfd);
uint8_t delete_device(int connfd);
void put_task(uint8_t dev_id, musictask_t *task);
void send_android_msg(int connfd, char msg[], int size);
void send_file(int connfd, FILE *fp);

#endif
